import { Request, Response, NextFunction } from 'express'
import { createUser, getUserById, updateUser } from './user.service'
import _ from 'lodash'

export const store = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { name, password } = req.body

  try {
    const data = await createUser({ name, password })
    res.send(data)
  } catch (error) {
    next(error)
  }
}

export const show = async (req: Request, res: Response, next: NextFunction) => {
  const { userId } = req.params

  try {
    const user = await getUserById(userId)
    if (!user) {
      return next(new Error('USER_NOT_FOUND'))
    }
    res.send(user)
  } catch (error) {
    next(error)
  }
}

export const update = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { id } = req.user
  const userData = _.pick(req.body.update, ['name', 'password'])

  try {
    const data = await updateUser(id, userData)
    res.send(data)
  } catch (error) {
    next(error)
  }
}
